package com.drd.dt.modular.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.drd.dt.common.tips.Tip;
import com.drd.dt.modular.service.HeiMaService;
import com.drd.dt.properties.TBLMPropertyConfig;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.TbkScPublisherInfoSaveRequest;
import com.taobao.api.request.TopAuthTokenCreateRequest;
import com.taobao.api.response.TbkScPublisherInfoSaveResponse;
import com.taobao.api.response.TopAuthTokenCreateResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMessage;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 通过黑马淘客授权创建订单
 */

@Api(tags = "黑马淘客", description = "通过黑马淘客授权创建订单")
@RestController
@RequestMapping("/api/v2/htsq/heima")
public class HeiMaController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private HeiMaService heiMaService;
    @Autowired
    private TBLMPropertyConfig tblmPropertyConfig;

    /**
     * 淘宝授权回调，获取授权码，然后去换token
     */
    @ApiOperation(value = "淘宝授权回调", notes = "获取授权码，然后去换token", response = HttpMessage.class)
    @GetMapping("/code")
    public Tip getCode(HttpServletRequest request) throws Exception {
        try {
            logger.info("回调CODE:" + request.getQueryString());
            String url = "https://eco.taobao.com/router/rest";
            String appkey = tblmPropertyConfig.getAppKey();
            String secret = tblmPropertyConfig.getAppSecret();
            String code = request.getParameter("code");
            TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
            TopAuthTokenCreateRequest req = new TopAuthTokenCreateRequest();
            req.setCode(code);
            TopAuthTokenCreateResponse rsp = client.execute(req);
            String resultStr = rsp.getBody();
            logger.info(resultStr);
            JSONObject resultObj = JSON.parseObject(resultStr);
            JSONObject data = resultObj.getJSONObject("top_auth_token_create_response").getJSONObject("token_result");
            String myid = request.getParameter("myid");
            String state = request.getParameter("state");
            if (StringUtils.isEmpty(myid)) {
                myid = state;
            }
            String token = data.getString("access_token");
            logger.info("【获取：myid:" + myid + "state:" + state + "token:" + token);
            String special_id = getSpecial_id(url, appkey, secret, token);
            String relation_id = getRelation_id(url, appkey, secret, token);
            String user_id = data.getString("taobao_user_id");
            String nikename = data.getString("taobao_user_nick");
            logger.info("获取：" + myid + " " + relation_id + " " + user_id + " " + special_id);
            Tip databack = heiMaService.getBackInfo(myid, relation_id, user_id, special_id, nikename);
            return databack;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("【淘宝回调备案错误】" + e);
        }
    }

    /**
     * 获取会员关系ID
     *
     * @return
     */
    private String getSpecial_id(String url, String appkey, String secret, String token) {
        try {
            TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
            TbkScPublisherInfoSaveRequest req3 = new TbkScPublisherInfoSaveRequest();
            req3.setRelationFrom("1");
            req3.setOfflineScene("1");
            req3.setOnlineScene("1");
            req3.setInviterCode("S8WNNX");//会员邀请码
            req3.setInfoType(1L);
            req3.setNote("核桃省钱");
            TbkScPublisherInfoSaveResponse rsp3 = client.execute(req3, token);
            String resultStr = rsp3.getBody();
            System.out.println(resultStr);
            JSONObject resultObj = JSON.parseObject(resultStr);
            JSONObject data = resultObj.getJSONObject("tbk_sc_publisher_info_save_response").getJSONObject("data");
            return data.getString("special_id");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取渠道关系ID
     *
     * @param url
     * @param appkey
     * @param secret
     * @param token
     * @return
     */
    private String getRelation_id(String url, String appkey, String secret, String token) {
        try {
            TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
            TbkScPublisherInfoSaveRequest req3 = new TbkScPublisherInfoSaveRequest();
            req3.setRelationFrom("1");
            req3.setOfflineScene("1");
            req3.setOnlineScene("1");
            req3.setInviterCode("VP2PCU");//渠道邀请码
            req3.setInfoType(1L);
            req3.setNote("核桃省钱");
            TbkScPublisherInfoSaveResponse rsp3 = client.execute(req3, token);
            String resultStr = rsp3.getBody();
            System.out.println(resultStr);
            JSONObject resultObj = JSON.parseObject(resultStr);
            JSONObject data = resultObj.getJSONObject("tbk_sc_publisher_info_save_response").getJSONObject("data");
            return data.getString("relation_id");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
